package lowijs.XfireClient.packet;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.*;

import java.io.*;
import java.net.*;

public class FriendGamePacket extends Packet {
	private final String gamedataUrl = 
		"http://domnious.com/michiel/gamedata.php";
	
	private String gamename;
	private byte[] image;
	
	public FriendGamePacket(byte[] data) {
		int numSids = fromLowHigh(data[9], data[10]);
		Friend[] friends = new Friend[numSids];
		int pos = 11;

		FriendManager fm = FriendManager.getInstance();

		for (int i = 0; i < numSids; i++) {
			byte[] sid = new byte[16];
			System.arraycopy(data, pos, sid, 0, 16);
			friends[i] = fm.getFriendBySid(sid);
			pos += 16;
		}

		pos += 11; // jump to the gameids

		for (int i = 0; i < numSids; i++) {
			int gameid = fromBytes(data, pos, 4);
			if (friends[i] != null) {
				if (gameid == 0)
					friends[i].setOutOfGame();
				else {
					getGamedataById(gameid);
					friends[i].setInGame(gamename, image);
				}
				EventManager.fireEvent(new FriendGameEvent(friends[i]));
			}
			pos += 4;
		}
	}
	
	private void getGamedataById(int gameid) {
		try {
			URL url = new URL(gamedataUrl + "?game=" + gameid);
			DataInputStream in =
				new DataInputStream(url.openStream());
	
			StringBuilder nameBuffer = new StringBuilder();
			byte b;
			
			while((b = in.readByte()) != 0x0A)
				nameBuffer.append((char)b);
			gamename = nameBuffer.toString();
			
			byte[] imageBuffer = new byte[4096];
			int read = in.read(imageBuffer, 0, imageBuffer.length);
			image = new byte[read];
			System.arraycopy(imageBuffer, 0, image, 0, read);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
